<?php


namespace app\api\model;


use function fast\e;
use fast\Random;
use think\Db;
use think\Model;

/**
 * 公司模型
 * Class Company
 * @package app\api\model
 */
class Company extends Model
{
    protected $createTime = 'createtime';
    protected $name = 'company';

    /**
     * 关联admin表
     * @return \think\model\relation\HasMany
     */
    public function admin(){
        return $this->hasMany('Admin','company_id','id');
    }

    /**
     * 公司注册
     * @param $data
     * @return bool
     * @throws \think\exception\PDOException
     */
    public function add($data){
        $data['validstarttime'] = strtotime($data['validstarttime']);
        $data['validendtime'] = strtotime($data['validendtime']);
        $data['builtime'] = strtotime($data['builtime']);
        $this->startTrans();
        try{
            // 新增管理员
            $params['salt'] = Random::alnum();
            $params['password'] = md5(md5('123456') . $params['salt']);
            $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
            $params['username'] = $data['phone'];
            $params['nickname'] = $data['phone'];
            $params['createtime'] = time();
            $admin_id =  $this->admin()->insertGetId($params);
            if ($admin_id){
                // 新增角色
                Db::name('AuthGroupAccess')->insert(['uid'=>$admin_id,'group_id'=>2]);
                $data['admin_id'] = $admin_id;
                $data['createtime'] = time();
                $this->allowField(true)->insertGetId($data);

                $this->admin()->where('id',$admin_id)->update(['admin_id'=>$admin_id]);
            }
            $this->commit();
            return true;
        }catch (\Exception $e){
            $this->rollback();
            $this->error = $e->getMessage();
            return false;
        }

    }
}